/**
 * 
 */
package com.hoopchina.util.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * @author Guo Baiyu
 *
 */
public class JsonEngine {
    private static final String	ENC_JSON	= "utf-8";

	/**
     * 
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String getJson( String url ) throws ClientProtocolException, IOException {
        String result = "";
        HttpGet httpGet = new HttpGet( url );
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = null;

        try {
            httpResponse = httpClient.execute( httpGet );
            HttpEntity httpEntity = httpResponse.getEntity();
            if ( httpEntity != null ) {
                InputStream inputStream = httpEntity.getContent();
                StringBuffer sb = new StringBuffer();
                BufferedReader br = new BufferedReader( new InputStreamReader( inputStream,
                		ENC_JSON ) );
                String data = "";

                while ( ( data = br.readLine() ) != null ) {
                    sb.append( data );
                }
                result = sb.toString();
            }
        }
        catch ( ClientProtocolException e ) {
            e.printStackTrace();
        }
        catch ( IOException e ) {
            throw e;
        }
        finally {
            httpClient.getConnectionManager().shutdown();
            httpResponse = null;
        }
        return result;
    }
    
    public static String getJsonStrFromFile(InputStream inputStream){
        StringBuffer sb = new StringBuffer();
        BufferedReader br;
        String result = "";
        try {
            br = new BufferedReader( new InputStreamReader( inputStream,
                    ENC_JSON ) );
       
        String data = "";
        
            while ( ( data = br.readLine() ) != null ) {
                sb.append( data );
            }
            result = sb.toString();
        }
        catch ( Exception e ) {
            result = "";
        }
        return result;
    }
}
